package org.example.datasource.eventhandler;

import java.io.IOException;
import java.util.Map;

import javax.annotation.PreDestroy;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.example.config.zk.ZookeeperConfiguration.ListenerContextService;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.CanalEntry.EventType;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbstractEventHandler implements EventHandler {
    private String REGISTRY_PATH = "/data-channel";
    @Autowired
    protected CuratorFramework curatorFramework;
    
    private static Map<String,EventHandler> handlerMap = Maps.newConcurrentMap();
    
    //<tableName,columns>
    protected Map<String,String> tables = Maps.newConcurrentMap();
    
    private PathChildrenCache pathChildrenCache;
    
    protected void register(String name,EventHandler handler) {
        handlerMap.put(name, handler);
    }
    protected void subscribe(String name) {
        String path = REGISTRY_PATH + "/" + name;
        log.info("订阅{}下变化",path);
//        try {
//            Stat stat = curatorFramework.checkExists().forPath(path);
//            if(stat==null) {//不存在则创建
//                curatorFramework.create().forPath(path);
//            }
//            curatorFramework.getChildren().usingWatcher(new CWatcherHandler(name, getHandler(name)))
//            .forPath(path);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        
     // 设置节点的cache
        pathChildrenCache = new PathChildrenCache(curatorFramework, path, false);
        pathChildrenCache.getListenable().addListener(new ListenerContextService(name,getHandler(name)));
        try {
            pathChildrenCache.start();
        } catch (Exception e) {
             e.printStackTrace();
        }
    }
    
    public static void check() {
        for(EventType type : CanalEntry.EventType.values()) {
            if(getHandler(type.name()) == null) {
                handlerMap.put(type.name(), defaultHandler);
            }
        }
    }
    
    private static DefaultHandler defaultHandler = new DefaultHandler();
    
    public static EventHandler getHandler(String name) {
        return handlerMap.get(name);
    }
    
    @PreDestroy
    public void destroy() {
        try {
            pathChildrenCache.close();
        } catch (IOException e) {
             log.error("destroy",e);
        }
        pathChildrenCache = null;
    }
}
